import 'dart:io';

import '../model/base_response.dart';
import '../model/cartoon_model.dart';
import '../model/cartoon_tab_model.dart';
import '../model/emotion_model.dart';
import '../model/message_record_model.dart';
import '../model/pipe_album_model.dart';
import '../model/pipe_comment_data.dart';
import '../model/pipe_model.dart';
import '../model/pipe_scene_model.dart';
import '../model/tab_data_model.dart';
import '../model/user_model.dart';
import '../service/auth_service.dart';
import 'api.dart';
import 'http_manager.dart';
import 'logger.dart';

class ApiService {
  static final ApiService _instance = ApiService._internal();

  factory ApiService() => _instance;

  ApiService._internal();

  String _apiUrl(String path) {
    return "${Api.BASE_URL}$path";
  }

  void getEmojiConfig(Function success, Function failure) {
    var url = _apiUrl(Api.EMOJI_CONFIG);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var list = (model.data as List<dynamic>).map((e) => EmotionModel.fromJson(e as Map<String, dynamic>)).toList();
          success(list);
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void login(LoginType loginType, String id, String pwd, Function success, Function failure) {
    Map<String, dynamic> params = {};
    params["loginType"] = loginType.value;
    params["openid"] = id;
    params["pwd"] = pwd;
    params["identity"] = 0;
    params["extraData"] = {"ref": "Android"};
    var url = _apiUrl(Api.LOGIN);
    HttpManager().post(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          success(model);
        } else {
          failure(model.msg);
        }
      } else {
        failure("请求失败");
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void uploadImage(File imageFile, Function success, Function failure) {
    var url = _apiUrl(Api.UPLOAD_IMAGE);
    HttpManager().uploadImage(url, imageFile).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          success(model.data);
        } else {
          failure();
        }
      } else {
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void uploadAudio(String filePath, Function success, Function failure) {
    var url = _apiUrl(Api.UPLOAD_AUDIO);
    HttpManager().uploadAudio(url, filePath).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          success(model.data);
        } else {
          failure();
        }
      } else {
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getHomeTagList(Function success, Function failure) {
    var url = _apiUrl(Api.TAG_LIST);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var list = (model.data as List<dynamic>).map((e) => TabDataModel.fromJson(e as Map<String, dynamic>)).toList();
          success(list);
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getTagPipeList(String tagId, int page, Function success, Function failure) {
    final String url = _apiUrl(Api.TAG_PIPE_LIST + tagId);
    final params = {"pageNo": page};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data as List<dynamic>).map((e) => PipeModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getCartoonTabId(Function success, Function failure) {
    var url = _apiUrl(Api.TAB_CARTOON);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var list = (model.data as List<dynamic>).map((e) => CartoonTabModel.fromJson(e as Map<String, dynamic>)).toList();
          var id = list.firstOrNull?.id ?? "";
          success(id);
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getCartoonList(String tabId, int page, Function success, Function failure) {
    final String url = _apiUrl('${Api.TAB_CARTOON}/$tabId');
    final params = {"pageNo": page};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var data = model.data as Map<String, dynamic>;
        var list = (data["list"] as List<dynamic>).map((e) => CartoonModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getRecommendCartoons(Function success, Function failure) {
    final String url = _apiUrl(Api.RCMD_FOLLOW_CARTOON);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data as List<dynamic>).map((e) => CartoonModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void followCartoon(String cartoonId, Function success, Function failure) {
    final String url = _apiUrl('${Api.FOLLOW_CARTOON}/$cartoonId');
    HttpManager().post(url).then((response) {
      if (response != null && response.data != null) {
        //BaseResponse model = BaseResponse.fromJson(response.data);
        success();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getFollowedCartoons(Function success, Function failure) {
    final String url = _apiUrl(Api.FOLLOW_CARTOON_LIST);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data as List<dynamic>).map((e) => CartoonModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getSearchHotWordList(Function success, Function failure) {
    final String url = _apiUrl(Api.SEARCH_HOT_WORD_LIST);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = model.data.cast<String>();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getRecommendPipeList(Function success, Function failure) {
    final String url = _apiUrl(Api.PIPE_RECOMMEND_LIST);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data as List<dynamic>).map((e) => PipeModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void searchPipeList(String text, int page, Function success, Function failure) {
    final String url = _apiUrl(Api.SEARCH_PIPE_LIST);
    final params = {"pageNo": page, "name": text};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data["list"] as List<dynamic>).map((e) => PipeModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void searchCartoonList(String text, int page, Function success, Function failure) {
    final String url = _apiUrl(Api.SEARCH_CARTOON_LIST);
    final params = {"pageNo": page, "name": text};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data["list"] as List<dynamic>).map((e) => CartoonModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void searchUserList(String text, int page, Function success, Function failure) {
    final String url = _apiUrl(Api.SEARCH_USER_LIST);
    final params = {"pageNo": page, "name": text};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var list = (model.data["list"] as List<dynamic>).map((e) => UserModel.fromJson(e as Map<String, dynamic>)).toList();
          success(list);
        } else {
          logger.e("请求数据失败，$model.msg");
        }
      } else {
        logger.e("请求数据失败");
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getPipeDetail(String pipeId, Function success, Function failure) {
    final String url = _apiUrl('${Api.PIPE_DETAIL}$pipeId');
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var pipeSceneModel = PipeSceneModel.fromJson(model.data);
          success(pipeSceneModel);
        } else {
          logger.e("请求数据失败，${model.msg}");
          failure(model.msg);
        }
      } else {
        logger.e("请求数据失败");
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }

  void sendMessage(Map<String, dynamic> params, Function success, Function failure) {
    final String url = _apiUrl(Api.SEND_MESSAGE);
    HttpManager().post(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          success(model.data);
        } else {
          logger.e("请求数据失败，${model.msg}");
          failure();
        }
      } else {
        logger.e("请求数据失败");
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getPipeAlbumProgress(String albumId, Function success, Function failure) {
    final String url = _apiUrl('${Api.PIPE_ALBUM_PROGRESS}$albumId');
    final params = {"albumId": albumId};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          print(model.data);
          var pipeAlbumModel = PipeAlbumModel.fromJson(model.data);
          success(pipeAlbumModel);
        } else {
          logger.e("请求数据失败，${model.msg}");
          failure();
        }
      } else {
        logger.e("请求数据失败");
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void resetChat(String pipeId, Function success, Function failure) {
    final String url = _apiUrl('${Api.RESET_CHAT}$pipeId');
    HttpManager().post(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          success();
        } else {
          logger.e("请求数据失败，${model.msg}");
          failure();
        }
      } else {
        logger.e("请求数据失败");
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getMessageRecordList(int pageNo, Function success, Function failure) {
    final String url = _apiUrl(Api.MESSAGE_RECORD_LIST);
    final params = {"pageNo": pageNo};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var list = (model.data["list"] as List<dynamic>).map((e) => MessageRecordModel.fromJson(e as Map<String, dynamic>)).toList();
          success(list);
        } else {
          logger.e("请求数据失败，${model.msg}");
          failure();
        }
      } else {
        logger.e("请求数据失败");
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getUserInfo(String uid, Function success, Function failure) {
    final String url = _apiUrl('${Api.GET_USER_INFO}$uid');
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.code == 0) {
          var user = UserModel.fromJson(model.data);
          success(user);
        } else {
          logger.e("请求数据失败，${model.msg}");
          failure();
        }
      } else {
        logger.e("请求数据失败");
        failure();
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getUserPipeList(String uid, Function success, Function failure) {
    final url = _apiUrl(Api.GET_USER_PIPE_LIST);
    final params = {"uid": uid};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data["list"] as List<dynamic>).map((e) => PipeModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getUserCartoonList(String uid, Function success, Function failure) {
    final url = _apiUrl(Api.GET_USER_CARTOON_LIST);
    final params = {"uid": uid};
    HttpManager().get(url, params: params).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        var list = (model.data["list"] as List<dynamic>).map((e) => CartoonModel.fromJson(e as Map<String, dynamic>)).toList();
        success(list);
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure();
    });
  }

  void getActivityInfo(Function success, Function failure) {
    final url = _apiUrl(Api.GET_ACTIVITY_BUTTON_INFO);
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.data != null) {
          success(model.data);
        } else {
          failure("请求数据失败");
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }

  void getCartoonInfo(String cartoonId, Function success, Function failure) {
    final url = _apiUrl("${Api.GET_CARTOON_INFO}$cartoonId");
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.data != null) {
          var cartoon = CartoonModel.fromJson(model.data["cartoon"]);
          success(cartoon);
        } else {
          failure("请求数据失败");
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }

  void getCartoonPipeList(String cartoonId, Function success, Function failure) {
    final url = _apiUrl("${Api.GET_CARTOON_INFO}$cartoonId/list");
    HttpManager().get(url).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.data != null) {
          var list = (model.data["list"] as List<dynamic>).map((e) => PipeModel.fromJson(e as Map<String, dynamic>)).toList();
          success(list);
        } else {
          failure("请求数据失败");
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }

  void getPipeCommentsCount(String pipeId, Function success, Function failure) {
    final url = _apiUrl(Api.GET_PIPE_COMMENTS_COUNT);
    HttpManager().get(url, params: {"pipeId": pipeId}).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.data != null) {
          success(model.data);
        } else {
          failure("请求数据失败");
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }

  void getPipeComments(String pipeId, int pageNo, Function success, Function failure) {
    final url = _apiUrl(Api.GET_PIPE_COMMENTS);
    HttpManager().get(url, params: {"pipeId": pipeId, "pageNo": pageNo}).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.data != null) {
          final data = PipeCommentData.fromJson(model.data);
          return success(data);
        } else {
          failure("请求数据失败");
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }

  void getPipeCommentReplyList(String pipeId, String pid, int pageNo, Function success, Function failure) {
    final url = _apiUrl(Api.GET_PIPE_COMMENTS);
    HttpManager().get(url, params: {"pipeId": pipeId, "pid": pid, "pageNo": pageNo}).then((response) {
      if (response != null && response.data != null) {
        BaseResponse model = BaseResponse.fromJson(response.data);
        if (model.data != null) {
          final data = PipeCommentData.fromJson(model.data);
          return success(data);
        } else {
          failure("请求数据失败");
        }
      }
    }).catchError((e, stackTrace) {
      logger.e("$e,$stackTrace");
      failure("请求数据失败");
    });
  }
}
